mod sms;

use serde::{de, Deserialize, Deserializer};
use std::{fmt, str::FromStr};

use sqlx::MySql;
use sqlx::Pool;

pub use sms::send_sms;
pub use sms::SmsMsg;

/// 根据uid判断是否是管理员
pub async fn check_admin(user_id: i32, pool: &Pool<MySql>) -> bool {
    match sqlx::query!("SELECT * FROM users WHERE id = ?", user_id)
        .fetch_one(pool)
        .await
    {
        Ok(v) => match v.is_admin {
            Some(v) => v != 0,
            None => false,
        },
        Err(e) => {
            log::error!("获取个人信息出错:{},id:{}", e, user_id);
            false
        }
    }
}

/// Serde deserialization decorator to map empty Strings to None,
pub fn empty_string_as_none<'de, D, T>(de: D) -> Result<Option<T>, D::Error>
where
    D: Deserializer<'de>,
    T: FromStr,
    T::Err: fmt::Display,
{
    let opt = Option::<String>::deserialize(de)?;
    match opt.as_deref() {
        None | Some("") => Ok(None),
        Some(s) => FromStr::from_str(s).map_err(de::Error::custom).map(Some),
    }
}
